<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RTSP流转换任务管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button.stop {
            background-color: #dc3545;
        }
        button.stop:hover {
            background-color: #c82333;
        }
        .task-list {
            margin-top: 30px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .status-probing {
            color: orange;
            font-weight: bold;
        }
        .status-running {
            color: green;
            font-weight: bold;
        }
        .status-stopped {
            color: red;
            font-weight: bold;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        .url-cell {
            word-break: break-all;
            max-width: 200px;
        }
        .copy-btn {
            background-color: #6c757d;
            color: white;
            padding: 3px 6px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }
        .copy-btn:hover {
            background-color: #5a6268;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>RTSP流转换任务管理</h1>
        
        <div class="form-section">
            <h2>启动新任务</h2>
            <div class="form-group">
                <label for="filename">任务名称:</label>
                <input type="text" id="filename" placeholder="请输入任务名称（不包含扩展名）">
            </div>
            <div class="form-group">
                <label for="rtspUrl">RTSP地址 (可选):</label>
                <input type="text" id="rtspUrl" placeholder="请输入RTSP地址，留空使用默认地址">
            </div>
            <button id="startBtn">启动任务</button>
        </div>
        
        <div class="task-list">
            <h2>当前任务列表</h2>
            <button id="refreshBtn">刷新列表</button>
            <table id="taskTable">
                <thead>
                    <tr>
                        <th>任务名称</th>
                        <th>状态</th>
                        <th>RTSP源地址</th>
                        <th>HLS地址</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="taskTableBody">
                    <!-- 任务列表将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
    </div>

    <script>
        // 页面加载完成后获取任务列表
        document.addEventListener('DOMContentLoaded', function() {
            refreshTaskList();
            
            // 绑定按钮事件
            document.getElementById('startBtn').addEventListener('click', startTask);
            document.getElementById('refreshBtn').addEventListener('click', refreshTaskList);
        });
        
        // 启动新任务
        function startTask() {
            const filename = document.getElementById('filename').value.trim();
            const rtspUrl = document.getElementById('rtspUrl').value.trim();
            
            if (!filename) {
                alert('请输入任务名称');
                return;
            }
            
            // 构造请求参数
            const formData = new FormData();
            formData.append('filename', filename);
            if (rtspUrl) {
                formData.append('rtspUrl', rtspUrl);
            }
            
            // 发送启动请求
            fetch('/stream/start', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                alert('任务启动成功');
                document.getElementById('filename').value = '';
                document.getElementById('rtspUrl').value = '';
                refreshTaskList();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('启动任务失败: ' + error.message);
            });
        }
        
        // 停止任务
        function stopTask(filename) {
            if (!confirm(`确定要停止任务 "${filename}" 吗？`)) {
                return;
            }
            
            // 发送停止请求
            const formData = new FormData();
            formData.append('filename', filename);
            
            fetch('/stream/stop', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                alert(data);
                refreshTaskList();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('停止任务失败: ' + error.message);
            });
        }
        
        // 复制文本到剪贴板
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(() => {
                alert('已复制到剪贴板: ' + text);
            }).catch(err => {
                console.error('复制失败: ', err);
                // 降级方案
                const textArea = document.createElement("textarea");
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                try {
                    document.execCommand('copy');
                    alert('已复制到剪贴板: ' + text);
                } catch (err) {
                    alert('复制失败，请手动复制: ' + text);
                }
                document.body.removeChild(textArea);
            });
        }
        
        // 根据状态获取显示文本和CSS类
        function getStatusDisplay(status) {
            switch(status) {
                case 'PROBING':
                    return { text: '探测中', cssClass: 'status-probing' };
                case 'RUNNING':
                    return { text: '运行中', cssClass: 'status-running' };
                case 'STOPPED':
                    return { text: '已停止', cssClass: 'status-stopped' };
                default:
                    return { text: status, cssClass: 'status-stopped' };
            }
        }
        
        // 刷新任务列表
        function refreshTaskList() {
            fetch('/stream/task-info')
            .then(response => response.json())
            .then(data => {
                const tableBody = document.getElementById('taskTableBody');
                tableBody.innerHTML = '';
                
                // 如果没有任务，显示提示信息
                if (Object.keys(data).length === 0) {
                    const row = tableBody.insertRow();
                    const cell = row.insertCell(0);
                    cell.colSpan = 5;
                    cell.textContent = '当前没有运行的任务';
                    cell.style.textAlign = 'center';
                    return;
                }
                
                // 遍历任务列表并添加到表格中
                for (const [filename, taskInfo] of Object.entries(data)) {
                    const row = tableBody.insertRow();
                    
                    // 任务名称
                    const nameCell = row.insertCell(0);
                    nameCell.textContent = filename;
                    
                    // 状态
                    const statusCell = row.insertCell(1);
                    const statusDisplay = getStatusDisplay(taskInfo.status);
                    statusCell.innerHTML = `<span class="${statusDisplay.cssClass}">${statusDisplay.text}</span>`;
                    
                    // RTSP地址
                    const rtspCell = row.insertCell(2);
                    rtspCell.className = 'url-cell';
                    const rtspCopyBtn = document.createElement('button');
                    rtspCopyBtn.className = 'copy-btn';
                    rtspCopyBtn.textContent = '复制';
                    rtspCopyBtn.onclick = () => copyToClipboard(taskInfo.rtspUrl);
                    rtspCell.textContent = taskInfo.rtspUrl + ' ';
                    rtspCell.appendChild(rtspCopyBtn);
                    
                    // HLS地址
                    const hlsCell = row.insertCell(3);
                    hlsCell.className = 'url-cell';
                    const hlsCopyBtn = document.createElement('button');
                    hlsCopyBtn.className = 'copy-btn';
                    hlsCopyBtn.textContent = '复制';
                    hlsCopyBtn.onclick = () => copyToClipboard(taskInfo.hlsUrl);
                    hlsCell.textContent = taskInfo.hlsUrl + ' ';
                    hlsCell.appendChild(hlsCopyBtn);
                    
                    // 操作按钮
                    const actionCell = row.insertCell(4);
                    actionCell.innerHTML = `
                        <div class="action-buttons">
                            <button class="stop" onclick="stopTask('${filename}')">停止</button>
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取任务列表失败: ' + error.message);
            });
        }
    </script>
</body>
</html>